/**
 * @api {get} /api/admin/v1/orders/analyse 订单统计
 * @apiGroup AdminOrders
 * @apiDescription 订单管理-订单统计
 * @apiPermission 管理员(查看订单权限)
 * @apiVersion 1.0.0
 */
exports.analyse = function ({}, {models: {TaokeOrders}}) {
    return TaokeOrders.analyseV2();
}

/**
 * @api {get} /api/admin/v1/orders/browse 订单列表
 * @apiGroup AdminOrders
 * @apiDescription 订单管理-订单列表
 * @apiPermission 管理员(查看订单权限)
 * @apiVersion 1.0.0
 */
let setAmountStatus = function (item) {
    let amountStatus;
    if (item.is_back) {
        amountStatus = '已退回';
    } else if (item.is_payed) {
        amountStatus = '已支付';
    } else if (item.is_settle) {
        amountStatus = '已结算';
    } else if (item.is_amount) {
        amountStatus = '已入账';
    } else {
        amountStatus = '待入账';
    }
    item.amount_status = amountStatus;
}
exports.browse = function ({query}, {models: {TaokeOrders, Users, associations}, controller}) {
    let pagination = controller.pagination({
        params: query,
        filters: ['id', 'partner_id', 'agency_id', 'user_id', 'auctionId', 'exNickName', 'exMemberId', 'shopTitle', 'payStatus', 'terminalType', 'adPositionId', 'mediumId', 'is_payed', 'is_back', 'taobaoTradeParentId', 'agency_settle_id'],
        likes: ['taobaoTradeParentId', 'user_id', 'agency_id']
    });
    if (!query.agency_settle_id) {
        if (query.has_settle_id === '0') {
            pagination.where.agency_settle_id = null;
        } else if (query.has_settle_id === '1') {
            pagination.where.agency_settle_id = {$ne: null};
        }
    }
    return TaokeOrders.findAndCountAll(pagination).then(function (data) {
        return associations.relateOne(data, Users, 'user_id', 'user', ['id', 'image', 'username', 'nickname', 'tel', 'order_count', 'finish_count', 'sham_count', 'amount', 'frozen']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'partner_id', 'partner', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function (data) {
        return associations.relateOne(data, Users, 'agency_id', 'agency', ['id', 'image', 'username', 'nickname', 'tel']);
    }).then(function (result) {
        let {rows, count} = result;
        for (let i in rows) {
            let row = rows[i];
            row.income = (parseFloat(row.feeString || 0) * 0.9 - parseFloat(row.pay_amount || 0) - parseFloat(row.agency_amount || 0) - parseFloat(row.inviter_pay_amount || 0) - parseFloat(row.inviter_agency_amount || 0)).toFixed(2);

            setAmountStatus(row);

            row.hasPayed = TaokeOrders.payedCheck(row);
        }
        return result;
    });
}
